package com.utils.httpclient;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;

public class HttpClientPost /* extends HttpClientAdapter*/{
	
	public static void main(String[] args) {
		
		String url = "https://kapi.xiaoniangao.cn/trends/get_recommend_trends";
		
		 Map<String, String> hearder = Maps.newHashMap();
		 hearder.put("Host","kapi.xiaoniangao.cn");
		 hearder.put("Connection","keep-alive");
//		 hearder.put("Content-Length", 1532);
		 hearder.put("Content-Type", "application/json;charset=utf-8");
		 hearder.put("User-Agent",
				 "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat");
		 hearder.put("uuid", "845833cc-10aa-4b5e-ba01-c9299fb0cd61");
		 hearder.put("Referer","https://servicewechat.com/wxd7911e4c177690e4/389/page-frame.html");
		 hearder.put("Accept-Encoding", "gzip, deflate, br");

//		 hearder.put("User-Agent", "PostmanRuntime/7.16.3");
//		 hearder.put("Postman-Token","f3ccbdd6-ff14-458b-8eef-e6ba35568277");
//		 hearder.put("Cache-Control", "max-age=0");
//		 hearder.put("Accept-Language", "zh-CN,zh;q=0.9");
//		 hearder.put("Accept",
//					"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
			
		
//		 Map<String, Object> maps = Maps.newHashMap();
//		 maps.put("dspId", 42);
//		 maps.put("sign", "651f7446780af7da504c70eee45619ae");
//		 maps.put("timestamp", 1571135341400l);
//		 maps.put("dataList", "");
		 
		String jsonStr = "{\"tag_id\":701,\"log_params\":{\"page\":\"discover_bless\",\"common\":{\"brand\":\"microsoft\",\"device\":\"microsoft\",\"os\":\"win10\",\"weixinver\":\"7.0.9\",\"srcver\":\"2.10.4\",\"net\":\"wifi\"}},\"log_common_params\":{\"e\":[{\"data\":{\"topic\":\"bless\",\"page\":\"discoverIndexPage\"}}],\"ext\":{\"brand\":\"microsoft\",\"device\":\"microsoft\",\"os\":\"win10\",\"weixinver\":\"7.0.9\",\"srcver\":\"2.10.4\",\"net\":\"wifi\"}},\"qs\":\"imageMogr2/gravity/center/rotate/$/thumbnail/!750x500r/crop/750x500/interlace/1/format/jpg\",\"h_qs\":\"imageMogr2/gravity/center/rotate/$/thumbnail/!80x80r/crop/80x80/interlace/1/format/jpg\",\"share_width\":625,\"share_height\":500,\"ext\":{\"items\":{\"7849028\":{\"type\":\"rec\",\"pd\":17.925601,\"ct\":1588745665363,\"ut\":1588745685144},\"8444834\":{\"type\":\"rec\",\"pd\":24.007427,\"ct\":1588745534420,\"ut\":1588745609202},\"9215569\":{\"type\":\"rec\",\"pd\":34.174618,\"ct\":1588745624995,\"ut\":1588745661407},\"9500647\":{\"type\":\"rec\",\"pd\":113.928482,\"ct\":1588745817010,\"ut\":1588745933188},\"10116663\":{\"type\":\"rec\",\"pd\":7.90634,\"ct\":1588745733790,\"ut\":1588745745608},\"10144546\":{\"type\":\"rec\",\"pd\":3.636682,\"ct\":1588745804772,\"ut\":1588745812154},\"15145929\":{\"type\":\"rec\",\"pd\":48.399562,\"ct\":1588747194769,\"ut\":1588747247275},\"17403682\":{\"type\":\"rec\",\"pd\":238.008856,\"ct\":1588746076777,\"ut\":1588747157860},\"18699838\":{\"type\":\"rec\",\"pd\":6.645809,\"ct\":1588745717634,\"ut\":1588745729175},\"19451140\":{\"type\":\"rec\",\"pd\":8.395938,\"ct\":1588747284879,\"ut\":1588747297938}}},\"token\":\"d2690a8e38d3f03f6e8a972962222dd5\",\"uid\":\"845833cc-10aa-4b5e-ba01-c9299fb0cd61\",\"proj\":\"ma\",\"wx_ver\":\"7.0.9\",\"code_ver\":\"2.9.1\"}";
		Object ret = JSONObject.parse(jsonStr);
		HttpClientPost.createDefaultHttpClient();
		HttpClientPost.setHeader(hearder);
		String str = HttpClientPost.sendHttpPost(url, ret);
		System.out.println(str);
	}
	
	
	private static PoolingHttpClientConnectionManager connMgr;  
    private static RequestConfig requestConfig;  
    private static int MAX_TIMEOUT = 15000;  
  
    static {  
        // 设置连接池  
        connMgr = new PoolingHttpClientConnectionManager();  
        // 设置连接池大小  
        connMgr.setMaxTotal(100);  
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());  
  
        RequestConfig.Builder configBuilder = RequestConfig.custom();  
        // 设置连接超时  
        configBuilder.setConnectTimeout(MAX_TIMEOUT);  
        // 设置读取超时  
        configBuilder.setSocketTimeout(MAX_TIMEOUT);  
        // 设置从连接池获取连接实例的超时  
        configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);  
        // 在提交请求之前 测试连接是否可用  
        configBuilder.setStaleConnectionCheckEnabled(true);  
        requestConfig = configBuilder.build();  
    }
    
    public static void setTimeOut(int timeOut) {
    	MAX_TIMEOUT = timeOut;
    }
//    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
//            .setConnectionRequestTimeout(15000).build();
    private static CloseableHttpClient  httpClient = HttpClients.createDefault();
    private static Map<String, String> header = new HashMap<String, String>();
    
    // 单例模式
/*    private static HttpClientPost instance = null;
    private HttpClientPost() {
    	
    }
    public static HttpClientPost getInstance() {
    	if (instance == null) {
    		instance = new HttpClientPost();
    	}
    	return instance;
    }*/
    
    public static void setHeader(Map<String, String> headers) {
    	headers.put("Content-Type", "text/html; charset=UTF-8");
    	headers.put("Accept", "text/html, application/xhtml+xml, image/jxr, */*");
    	headers.put("Accept-Language", "zh-CN");
    	headers.put("Connection", "Keep-Alive");
    	header = headers;
    }
    
	public static void creatHttpClient(String hostName, int port) {
		// 使用代理服务器
		httpClient = HttpClients.custom().setProxy(new HttpHost(hostName, port)).build();
	}

	public static void createDefaultHttpClient() {
		// 创建默认的httpClient实例
		httpClient = HttpClients.createDefault();
	}
	
	 /**
     * 发送 post请求
     * @param httpUrl 地址
     */
//    @Override
    public static String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param params  参数(格式:key1=value1&key2=value2)
     */
//    @Override
    public static String sendHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            StringEntity stringEntity = new StringEntity(params, "UTF-9=8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }
    
    /**
     * 发送 post请求
     * @param httpUrl
     * @param json  json对象
     * @return
     */
    public static String sendHttpPost(String httpUrl, Object json) {
    	HttpPost httpPost = new HttpPost(httpUrl);
        try {
            StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");
            stringEntity.setContentType("application/json");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * @param httpUrl 地址
     * @param maps 参数
     */
//    @Override
    public static String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求（带文件）
     * @param httpUrl 地址
     * @param maps  参数
     * @param fileLists 附件
     */
//    @Override
    public static String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
        HttpPost httpPost = new HttpPost(httpUrl);
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        for (String key : maps.keySet()) {
            meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
        }
        for (File file : fileLists) {
/*          meBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  
            meBuilder.addBinaryBody("file", in, ContentType.create("multipart/form-data"), "text.csv"); */
            FileBody fileBody = new FileBody(file);
            meBuilder.addPart("files", fileBody);
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendHttpPost(httpPost);
    }

    /**
     * 发送Post请求
     * @param httpPost
     * @return
     */
//    @Override
	private static String sendHttpPost(HttpPost httpPost) {
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            httpPost.setConfig(requestConfig);
            for (String key : header.keySet()) {
            	httpPost.addHeader(key, header.get(key));	
			}
            
            // 从头中取出转向的地址
//    	    Header locationHeader = httpPost.getFirstHeader("location");
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            
            int statusCode = response.getStatusLine().getStatusCode();
         // HttpClient对于要求接受后继服务的请求，象POST和PUT等不能自动处理转发
         // 301或者302
         if (statusCode == 307) {
             // 从头中取出转向的地址
        	 Header[] herads = response.getAllHeaders();
        	 for (int i = 0; i < herads.length; i++) {
				System.out.println(herads[i].getName()+"|||"+herads[i].getValue());
			}
             Header locationHeader = response.getFirstHeader("location");
             String location = null;
             if (locationHeader != null) {
              location = locationHeader.getValue();
              System.out.println("The page was redirected to:" + location);
             } else {
              System.err.println("Location field value is null.");
             }
         }
            
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }
}
